package com.morningstar.authorization.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.morningstar.authorization.controller.enitity.LoginEntity;
import com.morningstar.common.result.Result;
import com.morningstar.system.api.entity.SysUserFeign;
import com.morningstar.system.api.feign.ISystemUserFeign;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import static com.morningstar.common.result.ResultCode.USER_INFO_ERROR;
import static com.morningstar.common.result.ResultCode.USER_LOCKED;

@Service
public class LoginService {

    private static final String LOGIN_DEVICE_PC = "PC";

    @Resource
    ISystemUserFeign systemUserFeign;

    public Result<SaTokenInfo> login(LoginEntity loginEntity) throws Exception {
        SysUserFeign sysUserFeign = systemUserFeign.getUserByName(loginEntity.getName());
        if (ObjectUtils.isEmpty(sysUserFeign)) {
            return Result.fail(USER_INFO_ERROR);
        }
        if (StringUtils.equalsIgnoreCase(sysUserFeign.getStatus(), "1")) {
            return Result.fail(USER_LOCKED);
        }
        if (BCrypt.checkpw(loginEntity.getPwd(), sysUserFeign.getPassword())) {
            StpUtil.login(sysUserFeign.getUserId(), LOGIN_DEVICE_PC);
            return Result.successData(StpUtil.getTokenInfo());
        }
        return Result.fail(USER_INFO_ERROR);
    }

    public void logout() {
        StpUtil.logout();
    }
}
